package com.phalanxim.dao.impl;

import com.phalanxim.dao.AccountDao;
import com.phalanxim.service.*;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;


@Repository("accountDao")
public class AccountDaoImpl implements AccountDao
{
  @Autowired
  private SessionFactory sessionFactory;

  //Account Dao
  @Transactional(readOnly = true)
  public List<Account> getAccountList()
  {
    Session session = sessionFactory.openSession(); // not part of a transaction, so we need to open a session manually
    List<Account> accts = session.createQuery("from Account account").list();
    session.close();
    return accts;
  }

  @Transactional(readOnly = true)
  public Account findAccount(String id, boolean isLazy)
  {
    Session session = sessionFactory.openSession();
    Account acct = (Account)session.createCriteria(Account.class).add(Restrictions.eq("id", id)).uniqueResult();
    if(!isLazy)
    {
      for(Customer cst: acct.getCustomers());
    }
    session.close();
    return acct;
  }

  @Transactional
  public Account saveAccount(Account account)
  {
    Session session = sessionFactory.getCurrentSession();
    session.save(account);
    return account;
  }

  @Transactional
  public Account updateAccount(Account account)
  {
    Session session = sessionFactory.getCurrentSession();
    session.update(account);
    return account;
  }

  @Transactional
  public Account removeAccount(Account account)
  {
    Session session = sessionFactory.getCurrentSession();
    session.delete(account);
    return account;
  }

}
